package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
	@Autowired
	private AddressBookService addressBookService;

	@GetMapping("/list")
	public R<List<AddressBook>> list() {
		LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
		queryWrapper.orderByDesc(AddressBook::getUpdateTime);
		List<AddressBook> list = addressBookService.list(queryWrapper);
		return R.success(list);
	}

	@PostMapping
	public R<String> save(@RequestBody AddressBook addressBook){
		log.info("新增地址 {}",addressBook);
		Long userId = BaseContext.getCurrentId();
		addressBook.setUserId(userId);

		addressBookService.save(addressBook);
		return R.success("保存地址成功");
	}

	@PutMapping("/default")
	public R<String> isDefault(@RequestBody AddressBook addressBook){
		//1将当前用户的所有地址设置为非默认地址
		LambdaUpdateWrapper<AddressBook> updateWrapper1 = new LambdaUpdateWrapper<>();
		updateWrapper1.set(AddressBook::getIsDefault,0);
		updateWrapper1.eq(AddressBook::getUserId,BaseContext.getCurrentId());
		addressBookService.update(updateWrapper1);

		addressBook.setIsDefault(1);
		addressBookService.updateById(addressBook);

		return R.success("设置默认地址成功");
	}
	/**
	 * 根据id查询地址
	 */
	@GetMapping("/{id}")
	public R get(@PathVariable Long id) {
		AddressBook addressBook = addressBookService.getById(id);
		if (addressBook != null) {
			return R.success(addressBook);
		} else {
			return R.error("没有找到该对象");
		}
	}

	@PutMapping
	public R<String> update(@RequestBody AddressBook addressBook){
		log.info("修改地址消息",addressBook);
		addressBookService.updateById(addressBook);
		return R.success("修改地址成功");
	}

	@DeleteMapping
	public R<String> delete(Long ids){
		log.info("删除地址",ids);
		addressBookService.removeById(ids);
		return R.success("删除地址成功");
	}

	@GetMapping("/default")
	public R<AddressBook> getdefault(){
		//返回当前用户的用户地址
		//select * from adddress_book where user_id =? and is_default = 1;
		LambdaQueryWrapper<AddressBook> queryWrapper  = new LambdaQueryWrapper<>();
		queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
		queryWrapper.eq(AddressBook::getIsDefault,1);
		AddressBook addressBook = addressBookService.getOne(queryWrapper);

		if (addressBook==null){
			return R.error("该用户没有默认地址");
		}
		else return R.success(addressBook);
	}
}
